<template>
<div class="left-box" v-loading.fullscreen.lock="loadings">
    <div class="search-wrap search-inpt">
        <el-input clearable placeholder="搜索" v-model="filterText">
            <i slot="prefix" class="iconfont icon-sousuo"></i>
        </el-input>
    </div>
    <div class="scroll-bar">
        <el-tree default-expand-all @node-expand="nodeExpand" @node-collapse="nodeCollapse" v-loading="loading" element-loading-background="#f5f5f5" :data="treeData" :props="props" :filter-node-method="filterNode" ref="tree">
            <span class="node-span-wrap" slot-scope="{data}" @contextmenu="contexMenuItem=data;contextMenu($event)">
                <el-tooltip :open-delay="1000" :enterable="false" effect="dark" :content="data.name" placement="bottom">
                    <span class="tree-node-span" :draggable="getChilren(data)" @dragover.prevent @dragstart="dragstart($event, data)" :class="{'is-component': getChilren(data)}">
                        <i :style="{color: colors[data.iconType]}" class="tree-node-icon" :class="`iconfont ${data.iconType}`"></i>
                        <span>{{data.name}}</span>
                    </span>
                </el-tooltip>
            </span>
        </el-tree>
    </div>
    <easy-cm tag="ModelList" :itemHeight="32" :itemSize="12" :list="cmList" @ecmcb="handleClickMenu" :underline="false" :arrow="true"></easy-cm>
    <confirm-dialog @save="confirmSave" :confirmObj="confirmObj">
        <template v-if="confirmObj.title === '保存模型'">
            <div style="padding-top:16px;display:flex;">
                <span style="padding-right:12px;">描述</span>
                <el-input :maxlength="100" type="textarea" :rows="5" clearable placeholder="请输入描述" v-model="description"></el-input>
            </div>
        </template>
    </confirm-dialog>
    <detail-dialog v-if="detail.show" :detail="detail"></detail-dialog>
</div>
</template>

<script>
import {
    colors
} from '@/js/tool'
import ConfirmDialog from '@/components/ConfirmDialog'
import detailDialog from '@/views/detail'
import {
    mapMutations,
    mapGetters
} from 'vuex'
export default {
    name: 'ModelList',
    components: {
        ConfirmDialog,
        detailDialog
    },
    data () {
        return {
            isReName: false,
            colors,
            description: null,
            cmList: null,
            props: {
                label: 'name'
            },
            loading: false,
            filterText: '',
            treeData: [],
            list: [
                {
                    text: '导出PMML',
                    icon: 'iconfont icon-daochu',
                    key: 'exportPMML'
                },
                {
                    text: '查看模型',
                    icon: 'iconfont icon-chakanmoxing',
                    key: 'checkModel'
                },
                {
                    text: '保存模型',
                    icon: 'iconfont icon-baocunshiyanfuben',
                    key: 'saveModel'
                },
                {
                    text: '重命名',
                    icon: 'iconfont icon-zhongmingming',
                    key: 'reName'
                },
                {
                    text: '删除',
                    icon: 'iconfont icon-shanchu',
                    key: 'removeModel'
                },
                {
                    text: '定位到实验',
                    icon: 'iconfont icon-dingweimoxing',
                    key: 'goExp'
                }
            ],
            contexMenuItem: null,
            confirmObj: {
                show: false,
                title: '重命名',
                size: 64,
                value: '',
                placeholder: '请输入模型名称'
            },
            detail: {
                show: false
            },
            loadings: false
        }
    },
    watch: {
        filterText (val) {
            this.$refs.tree.filter(val)
        },
        updateModel () {
            this.init()
        }
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            updateModel: 'common/getUpdateModel'
        })
    },
    created () {
        this.init()
    },
    methods: {
        ...mapMutations({
            setModelDetail: 'common/setModelDetail',
            setTypeId: 'common/setTypeId',
            setNewExp: 'common/setNewExp'
        }),
        getChilren (data) {
            return !data.children || data.children.length === 0
        },
        nodeCollapse (item) {
            if (item.isFolder) {
                item.iconType = 'icon-catalog-close'
            }
        },
        nodeExpand (item) {
            if (item.isFolder) {
                item.iconType = 'icon-catalog-open'
            }
        },
        init () {
            this.loading = true
            const parmas = {
                keyword: '',
                projectId: this.projectId
            }
            this.$post('/experiment/catalog/queryModelSourceCatalog', parmas).then(res => {
                if (res) {
                    const {
                        modelTrees,
                        savedModels
                    } = res
                    this.treeData = []
                    if (savedModels.length) {
                        savedModels.forEach(v => {
                            v.name = v.modelName
                            v.iconType = 'icon-module-source-destination'
                            v.i = 0
                        })
                        this.treeData.push({
                            name: '已保存模型',
                            isFolder: true,
                            iconType: 'icon-catalog-open',
                            children: savedModels
                        })
                    } else {
                        this.treeData.push({
                            name: '已保存模型',
                            isFolder: true,
                            iconType: 'icon-catalog-open',
                            children: []
                        })
                    }
                    if (modelTrees.length) {
                        modelTrees.forEach(v => {
                            v.name = v.experimentName
                            v.iconType = 'icon-moxing_shiyan'
                            v.models.length && v.models.forEach(p => {
                                p.name = p.modelName
                                p.iconType = 'icon-module-source-destination'
                                p.i = 1
                            })
                            v.children = v.models
                        })
                        this.treeData.push({
                            name: '实验模型',
                            isFolder: true,
                            iconType: 'icon-catalog-open',
                            children: modelTrees
                        })
                    } else {
                        this.treeData.push({
                            name: '实验模型',
                            isFolder: true,
                            iconType: 'icon-catalog-open',
                            children: []
                        })
                    }
                }
            }).finally(() => {
                this.loading = false
            })
        },
        dragstart (e, item) {
            e.dataTransfer.setData('item', JSON.stringify(item))
        },
        filterNode (value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        contextMenu (e) {
            const { modelId, i, refAlgorithmId } = this.contexMenuItem
            if (modelId) {
                let arr = JSON.parse(JSON.stringify(this.list))
                if (i === 0) {
                    arr.splice(2, 1)
                } else {
                    if (refAlgorithmId > 100 && refAlgorithmId < 106) {
                        arr.splice(1, 4)
                    } else {
                        arr.splice(3, 2)
                    }
                }
                this.cmList = arr
                this.$easycm(e, this.$root, 'ModelList')
            }
        },
        exportPMML () {
            this.$message.warning('此功能正在开发中，敬请期待!')
        },
        checkModel () {
            let {
                modelId
            } = this.contexMenuItem
            const params = {
                modelId,
                projectId: this.projectId
            }
            this.loadings = true
            this.$post('/modelSource/viewModel', params).then(res => {
                if (res) {
                    this.setModelDetail(res)
                    this.detail.show = true
                }
            }).finally(() => {
                this.loadings = false
            })
        },
        saveModel () {
            this.isReName = false
            this.description = null
            this.confirmObj = {
                show: true,
                title: '保存模型',
                placeholder: '请输入模型名称',
                size: 64,
                value: this.contexMenuItem.name,
                leftTitle: '名称'
            }
        },
        reName () {
            this.isReName = true
            this.confirmObj = {
                show: true,
                title: '重命名',
                placeholder: '请输入模型名称',
                size: 64,
                value: this.contexMenuItem.name,
                leftTitle: '名称'
            }
        },
        confrimReName (value) {
            let {
                modelId
            } = this.contexMenuItem
            this.$post('/modelSource/renameModel', {
                projectId: this.projectId,
                modelId: modelId,
                modelName: value
            }).then(res => {
                if (res) {
                    this.confirmObj.show = false
                    this.$message.success('保存成功')
                    this.init()
                }
            })
        },
        confirmSave (value) {
            this.isReName ? this.confrimReName(value) : this.handleSaveModel(value)
        },
        removeModel () {
            this.$confirm(`确定要删除模型<span>[${this.contexMenuItem.modelName}]</span>吗？`, '提示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                dangerouslyUseHTMLString: true,
                type: 'warning'
            }).then(() => {
                const params = {
                    projectId: this.projectId,
                    modelIds: [this.contexMenuItem.modelId]
                }
                this.$post('/modelSource/deleteModel', params).then(res => {
                    if (res) {
                        this.$message.success('删除成功')
                        this.init()
                    }
                })
            }).catch(() => {})
        },
        handleSaveModel (value) {
            const { experimentId, modelId } = this.contexMenuItem
            let params = {
                experimentId,
                projectId: this.projectId,
                modelId,
                newModelName: value,
                description: this.description
            }
            this.$post('/modelSource/saveTempModel', params).then(res => {
                if (res) {
                    this.init()
                    this.confirmObj.show = false
                    this.$message.success('保存成功')
                }
            })
        },
        goExp () {
            this.setTypeId(0)
            this.$message.success('定位成功')
            setTimeout(() => {
                this.setNewExp(this.contexMenuItem.experimentId)
            }, 500)
        },
        handleClickMenu ([index], item) {
            this[item.key]()
        }
    }
}
</script>
